package com.yang.service.wximpl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.yang.bean.*;
import com.yang.bean.common.BaseParam;
import com.yang.bean.common.BaseRespVo;
import com.yang.bean.common.CommonData;
import com.yang.bean.dhr.*;
import com.yang.mapper.*;
import com.yang.service.wx.WxOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import java.math.BigDecimal;
import java.util.*;


/**
 * @author dinghongrui
 * @create 2022/09/09 17:19
 */
@Service
public class WxOrderServiceImpl implements WxOrderService {
    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;


    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Override
    public CommonData queryAllList(Integer showType, BaseParam baseParam,Integer id) {
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        MarketOrderExample example = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (showType == 1) {
            criteria.andOrderStatusEqualTo((short) 101);
        } else if (showType == 2) {
            criteria.andOrderStatusEqualTo((short) 201);
        } else if (showType == 3) {
            criteria.andOrderStatusEqualTo((short) 301);
        } else if (showType == 4) {
            criteria.andOrderStatusEqualTo((short) 401);
        }
        criteria.andUserIdEqualTo(id);

        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(example);
        PageInfo<MarketOrder> pageInfo = new PageInfo<>(marketOrders);
        CommonData commonData = new CommonData();
        commonData.setTotal((int) pageInfo.getTotal());
        commonData.setPage(pageInfo.getPageNum());
        commonData.setPages(pageInfo.getPages());
        commonData.setLimit(pageInfo.getPageSize());
        List<MarketOrderListVo> listVos = new ArrayList<>();
        /*if ("1".equals(1)) {
            System.out.println("true");
        }*/
        for (MarketOrder marketOrder : marketOrders) {
            MarketOrderListVo orderListVo = new MarketOrderListVo();
            if (101 == marketOrder.getOrderStatus()) {
                orderListVo.setOrderStatusText("待付款");
            } else if (102 == marketOrder.getOrderStatus()) {
                orderListVo.setOrderStatusText("用户取消");
            } else if (103 == marketOrder.getOrderStatus()) {
                orderListVo.setOrderStatusText("系统取消");
            }else if (201 == marketOrder.getOrderStatus()) {
                orderListVo.setOrderStatusText("已付款");
            }else if (202 == marketOrder.getOrderStatus()) {
                orderListVo.setOrderStatusText("订单取消，退款中");
            }else if (203 == marketOrder.getOrderStatus()) {
                orderListVo.setOrderStatusText("已退款");
            }else if (301 == marketOrder.getOrderStatus()) {
                orderListVo.setOrderStatusText("已发货");
            }else if (401 == marketOrder.getOrderStatus()) {
                orderListVo.setOrderStatusText("已收货");
            }else if (402 == marketOrder.getOrderStatus()) {
                orderListVo.setOrderStatusText("系统收货");
            }
            orderListVo.setAftersaleStatus(marketOrder.getAftersaleStatus());
            orderListVo.setIsGroupin(false);
            orderListVo.setOrderSn(marketOrder.getOrderSn());
            orderListVo.setActualPrice(marketOrder.getActualPrice());
            orderListVo.setId(marketOrder.getId());
            HandleOptionEntityVo optionEntityVo = new HandleOptionEntityVo();
            if (101 == marketOrder.getOrderStatus()) {
                optionEntityVo.setCancel(true);
                optionEntityVo.setPay(true);
            }else {
                optionEntityVo.setCancel(false);
                optionEntityVo.setPay(false);
            }

            if (401 == marketOrder.getOrderStatus()) {
                optionEntityVo.setDelete(true);
            } else {
                optionEntityVo.setDelete(false);
            }

            if (401 == marketOrder.getOrderStatus()) {
                optionEntityVo.setRebuy(true);
            } else {
                optionEntityVo.setRebuy(false);
            }
            if (301 == marketOrder.getOrderStatus()) {
                optionEntityVo.setConfirm(true);
            } else {
                optionEntityVo.setConfirm(false);
            }
            if (401 == marketOrder.getOrderStatus()) {
                optionEntityVo.setAftersale(true);
            } else {
                optionEntityVo.setAftersale(false);
            }
            if (201 == marketOrder.getOrderStatus()) {
                optionEntityVo.setRefund(true);
            } else {
                optionEntityVo.setRefund(false);
            }
            if (401 == marketOrder.getOrderStatus()) {
                optionEntityVo.setComment(true);
            } else {
                optionEntityVo.setComment(false);
            }
            MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria orderGoodsCriteria= orderGoodsExample.createCriteria();
            orderGoodsCriteria.andOrderIdEqualTo(marketOrder.getId());
            List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(orderGoodsExample);
            List<GoodsListEntityVo> goodsListEntityVos = new ArrayList<>();
            for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
                GoodsListEntityVo goodsListEntityVo = new GoodsListEntityVo();
                goodsListEntityVo.setNumber(marketOrderGood.getNumber());
                goodsListEntityVo.setPicUrl(marketOrderGood.getPicUrl());
                goodsListEntityVo.setPrice(marketOrderGood.getPrice());
                goodsListEntityVo.setId(marketOrderGood.getId());
                goodsListEntityVo.setGoodsName(marketOrderGood.getGoodsName());
                String[] specifications = marketOrderGood.getSpecifications();
                List<String> strings = Arrays.asList(specifications);
                goodsListEntityVo.setSpecifications(strings);
                goodsListEntityVos.add(goodsListEntityVo);
            }
            orderListVo.setHandleOption(optionEntityVo);
            orderListVo.setGoodsList(goodsListEntityVos);
            listVos.add(orderListVo);
        }
        commonData.setList(listVos);
        return commonData;
    }

    @Override
    public BaseRespVo queryDetails(Integer orderId) {
        MarketOrderDetail detail = new MarketOrderDetail();
        String[] expressInfo = {};
//        detail.setExpressInfo(new String[]{});
        detail.setExpressInfo(expressInfo);

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        OrderInfo orderInfo = new OrderInfo();
        if (marketOrder.getOrderStatus() >= 301) {
            orderInfo.setExpNo(marketOrder.getShipSn());
            orderInfo.setExpCode(marketOrder.getShipChannel());
            if ("ZTO".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("中通快递");
            } else if ("YTO".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("圆通速递");
            }else if ("YUNDA".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("韵达速递");
            }else if ("Postal Parcel".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("邮政快递包裹");
            }else if ("EMS".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("中国邮政");
            }else if ("DEPPON".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("德邦快递");
            }else if ("FASTEXPRESS".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("快捷快递");
            }else if ("ZJS".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("宅急送");
            }else if ("TNT".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("TNT快递");
            }else if ("UPS".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("UPS");
            }else if ("DHL".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("DHL");
            }else if ("FEDEX".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("FEDEX联邦(国内件)");
            }else if ("FedEx".equals(marketOrder.getShipChannel())) {
                orderInfo.setExpName("FEDEX联邦(国际件)");
            }
        }

        orderInfo.setConsignee(marketOrder.getConsignee());
        orderInfo.setAddress(marketOrder.getAddress());
        orderInfo.setAddTime(marketOrder.getAddTime());
        orderInfo.setOrderSn(marketOrder.getOrderSn());
        orderInfo.setActualPrice(marketOrder.getActualPrice());
        orderInfo.setMobile(marketOrder.getMobile());
        orderInfo.setMessage(marketOrder.getMessage());
        if (101 == marketOrder.getOrderStatus()) {
            orderInfo.setOrderStatusText("待付款");
        } else if (102 == marketOrder.getOrderStatus()) {
            orderInfo.setOrderStatusText("用户取消");
        } else if (103 == marketOrder.getOrderStatus()) {
            orderInfo.setOrderStatusText("系统取消");
        }else if (201 == marketOrder.getOrderStatus()) {
            orderInfo.setOrderStatusText("已付款");
        }else if (202 == marketOrder.getOrderStatus()) {
            orderInfo.setOrderStatusText("订单取消，退款中");
        }else if (203 == marketOrder.getOrderStatus()) {
            orderInfo.setOrderStatusText("已退款");
        }else if (301 == marketOrder.getOrderStatus()) {
            orderInfo.setOrderStatusText("已发货");
        }else if (401 == marketOrder.getOrderStatus()) {
            orderInfo.setOrderStatusText("已收货");
        }else if (402 == marketOrder.getOrderStatus()) {
            orderInfo.setOrderStatusText("系统收货");
        }
        orderInfo.setAftersaleStatus(marketOrder.getAftersaleStatus());
        orderInfo.setGoodsPrice(marketOrder.getGoodsPrice());
        orderInfo.setCouponPrice(marketOrder.getCouponPrice());
        orderInfo.setId(marketOrder.getId());
        orderInfo.setFreightPrice(marketOrder.getFreightPrice());
        HandleOptionEntityVo optionEntityVo = new HandleOptionEntityVo();
        if (101 == marketOrder.getOrderStatus()) {
            optionEntityVo.setCancel(true);
            optionEntityVo.setPay(true);
        }else {
            optionEntityVo.setCancel(false);
            optionEntityVo.setPay(false);
        }

        if (401 == marketOrder.getOrderStatus() || 203 == marketOrder.getOrderStatus()) {
            optionEntityVo.setDelete(true);
        } else {
            optionEntityVo.setDelete(false);
        }

        if (401 == marketOrder.getOrderStatus()) {
            optionEntityVo.setRebuy(true);
        } else {
            optionEntityVo.setRebuy(false);
        }
        if (301 == marketOrder.getOrderStatus()) {
            optionEntityVo.setConfirm(true);
        } else {
            optionEntityVo.setConfirm(false);
        }
        if (401 == marketOrder.getOrderStatus()) {
            optionEntityVo.setAftersale(true);
        } else {
            optionEntityVo.setAftersale(false);
        }
        if (201 == marketOrder.getOrderStatus()) {
            optionEntityVo.setRefund(true);
        } else {
            optionEntityVo.setRefund(false);
        }
        if (401 == marketOrder.getOrderStatus()) {
            optionEntityVo.setComment(true);
        } else {
            optionEntityVo.setComment(false);
        }
        orderInfo.setHandleOption(optionEntityVo);
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> orderGoodsList = marketOrderGoodsMapper.selectByExample(example);
        detail.setOrderInfo(orderInfo);
        detail.setOrderGoods(orderGoodsList);

        BaseRespVo<Object> baseRespVo = new BaseRespVo<>();
        baseRespVo.setData(detail);
        baseRespVo.setErrmsg("成功");
        baseRespVo.setErrno(0);
        return baseRespVo;
    }

    @Override
    public void refund(Map map) {
        Integer orderId = (Integer) map.get("orderId");
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 202);
        marketOrder.setAftersaleStatus((short) 1);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public void delete(Map map) {
        Integer orderId = (Integer) map.get("orderId");
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setDeleted(true);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public void confirm(Map map) {
        Integer orderId = (Integer) map.get("orderId");
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 401);
        marketOrder.setConfirmTime(new Date());
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public int comment(MarketCommentBo marketCommentBo) {


        MarketOrderGoods orderGoods = marketOrderGoodsMapper.selectByPrimaryKey(marketCommentBo.getOrderGoodsId());
        MarketComment marketComment = new MarketComment();
        marketComment.setContent(marketCommentBo.getContent());
        marketComment.setStar(marketCommentBo.getStar());
        marketComment.setHasPicture(marketCommentBo.getHasPicture());
        marketComment.setPicUrls(marketCommentBo.getPicUrls());
        marketComment.setType((byte) 0);

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderGoods.getOrderId());
        marketComment.setUserId(marketOrder.getUserId());
        if (orderGoods.getComment() == -1) {
            return 404;
        } else if (orderGoods.getComment() == 0) {
            marketComment.setValueId(orderGoods.getGoodsId());
            Date date = new Date();
            marketComment.setAddTime(date);
            marketComment.setUpdateTime(date);
            marketComment.setDeleted(false);
            marketCommentMapper.insertSelective(marketComment);
            MarketOrderGoods orderGoods1 = new MarketOrderGoods();
            orderGoods1.setComment(marketComment.getId());
            orderGoods1.setId(marketCommentBo.getOrderGoodsId());
            marketOrderGoodsMapper.updateByPrimaryKeySelective(orderGoods1);
        }
        return 200;
    }

    @Override
    public void cancel(Map map) {
        Integer orderId = (Integer) map.get("orderId");
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short) 102);
        marketOrder.setId(orderId);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public BaseRespVo returnGoodMsg(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example);
        MarketOrderGoods orderGoods = new MarketOrderGoods();
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            orderGoods = marketOrderGood;
        }

        return BaseRespVo.ok(orderGoods);

    }

    @Override
    public BaseRespVo submit(MarketSubmitBo marketSubmitBo) {
        Integer cartId = marketSubmitBo.getCartId();
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andCheckedEqualTo(true).andDeletedEqualTo(false);
        if (cartId != null || cartId != 0) {
            criteria.andIdEqualTo(cartId);
        }
//        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(cartId);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(example);
        BigDecimal goodsPrice = BigDecimal.valueOf(0);
        Short number = 0;
        for (MarketCart marketCart : marketCarts) {
            MarketGoodsProduct goodsProduct = marketGoodsProductMapper.selectByPrimaryKey(marketCart.getProductId());
           if (marketCart.getNumber() > goodsProduct.getNumber()) {
               return BaseRespVo.error("库存不足");
           }
           goodsPrice = goodsPrice.add(goodsProduct.getPrice());
           number = (short)(number + marketCart.getNumber());
        }

//        Short number = marketCart.getNumber();
//        MarketGoodsProduct goodsProduct = marketGoodsProductMapper.selectByPrimaryKey(marketCart.getProductId());
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(marketSubmitBo.getAddressId());
        String name = marketAddress.getName();
        String tel = marketAddress.getTel();
        Integer userId = marketAddress.getUserId();
        String address = marketAddress.getProvince() + marketAddress.getCity() + marketAddress.getAddressDetail();
        BigDecimal freightPrice = BigDecimal.valueOf(15);
        BigDecimal couponPrice = BigDecimal.valueOf(0);
        BigDecimal integralPrice = BigDecimal.valueOf(0);
        BigDecimal grouponPrice = BigDecimal.valueOf(0);
        BigDecimal orderPrice =goodsPrice;
        Integer couponId = marketSubmitBo.getCouponId();
        if (couponId == null || couponId == 0) {
            couponPrice = BigDecimal.valueOf(0);
        }
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
        couponPrice = marketCoupon.getDiscount();
        orderPrice = freightPrice.add(orderPrice);
        BigDecimal actualPrice = orderPrice.subtract(couponPrice);
        Date date = new Date();
        MarketOrder marketOrder = new MarketOrder(null,userId,date.toString(),(short)101,(short)0,name,tel,address,marketSubmitBo.getMessage(),goodsPrice,freightPrice,couponPrice,integralPrice,grouponPrice,orderPrice,actualPrice,null,null,null,null,null,null,null,
                null,null,null,number,null,date,date,false);
        //把marketOrder插入订单表
        marketOrderMapper.insert(marketOrder);
        Integer orderId = marketOrder.getId();
        //向订单商品表插入数据
        for (MarketCart marketCart : marketCarts) {
            Integer goodsId = marketCart.getGoodsId();
            String goodsName = marketCart.getGoodsName();
            String goodsSn = marketCart.getGoodsSn();
            Integer productId = marketCart.getProductId();
            int number1 = marketCart.getNumber();
            short number2 = (short)number1;
//            Short number1 = Short.valueOf(marketCart.getNumber().toString());
            BigDecimal price = marketCart.getPrice();
            String[] specifications = marketCart.getSpecifications();
            String picUrl = marketCart.getPicUrl();
            Date date1 = new Date();
            MarketOrderGoods orderGoods = new MarketOrderGoods(null,orderId,goodsId,goodsName,goodsSn,productId,
                    number2,price,specifications,picUrl,0,date1,date1,false);
            marketOrderGoodsMapper.insert(orderGoods);
        }
        //修改购物车
        MarketCart cart = new MarketCart();
        cart.setId(cartId);
        cart.setUpdateTime(new Date());
        cart.setDeleted(true);
        marketCartMapper.updateByPrimaryKeySelective(cart);
        //更新优惠券使用情况
        if (couponId != null && couponId != 0) {
            MarketCouponUser marketCouponUser = new MarketCouponUser();
            marketCouponUser.setId(marketSubmitBo.getUserCouponId());
            marketCouponUser.setStatus((short) 1);
            marketCouponUser.setUsedTime(date);
            marketCouponUser.setOrderId(orderId);
            marketCouponUser.setDeleted(true);
            marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser);
        }
        //更新库存
        for (MarketCart marketCart : marketCarts) {
            MarketGoodsProduct goodsProduct = marketGoodsProductMapper.selectByPrimaryKey(marketCart.getProductId());
            Integer leftNumber = goodsProduct.getNumber()-marketCart.getNumber();
            Integer productId = marketCart.getProductId();
            MarketGoodsProduct product = new MarketGoodsProduct();
            product.setId(productId);
            product.setNumber(leftNumber);
            product.setUpdateTime(date);
            marketGoodsProductMapper.updateByPrimaryKeySelective(product);
        }

        MarketSubmitVo submitVo = new MarketSubmitVo();
        submitVo.setOrderId(marketOrder.getId());
        submitVo.setGrouponLinkId(marketSubmitBo.getGrouponLinkId());

        return BaseRespVo.ok(submitVo);
    }

    @Override
    public void prepay(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 201);
        Date date = new Date();
        marketOrder.setPayTime(date);
        marketOrder.setUpdateTime(date);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }
}
